// =====================
// 🎯 泛型类示例
// =====================
class Box<T> {
  T value;

  Box(this.value);

  void showType() {
    print("This box holds a value of type: ${value.runtimeType}");
  }

  T getValue() => value;
}

// =====================
// 🧩 泛型函数示例
// =====================
T getFirst<T>(List<T> items) {
  return items.isNotEmpty ? items.first : throw Exception("List is empty");
}

// =====================
// 🦊 泛型约束示例
// =====================
abstract class Animal {
  void sound();
}

class Dog extends Animal {
  @override
  void sound() => print("Woof! 🐶");
}

class Cat extends Animal {
  @override
  void sound() => print("Meow! 🐱");
}

// 受限泛型类：仅允许 Animal 子类
class Zoo<T extends Animal> {
  final List<T> animals = [];

  void add(T animal) {
    animals.add(animal);
  }

  void makeSounds() {
    for (var a in animals) {
      a.sound();
    }
  }
}

// =====================
// 📦 泛型集合示例
// =====================
void showGenericCollections() {
  // 泛型 List
  List<int> numbers = [1, 2, 3, 4, 5];
  print("List<int>: $numbers");

  // 泛型 Map
  Map<String, int> scores = {"Alice": 95, "Bob": 88, "Charlie": 76};
  print("Map<String, int>: $scores");

  // 泛型 Set
  Set<String> fruits = {"Apple", "Banana", "Orange"};
  print("Set<String>: $fruits");

  // 泛型推断
  var mixed = <dynamic>["Dart", 2025, true];
  print("List<dynamic>: $mixed");
}

// =====================
// 🧠 主函数入口
// =====================
void main() {
  // 泛型类
  var intBox = Box<int>(123);
  intBox.showType(); // int

  var strBox = Box<String>("Hello Dart");
  strBox.showType(); // String

  print("------");

  // 泛型函数
  var first = getFirst<String>(["A", "B", "C"]);
  print("First element: $first");

  print("------");

  // 泛型约束类
  var zoo = Zoo<Animal>();
  zoo.add(Dog());
  zoo.add(Cat());
  zoo.makeSounds(); // Woof! 🐶 Meow! 🐱

  print("------");

  // 泛型集合
  showGenericCollections();
}
